//
// Created by v on 19-7-8.
//

#include <unistd.h>

#include "CMLock.h"

CMLock::CMLock()
{
    pthread_mutex_init(&m_mutex, NULL);
    m_printInterval = 15;
}

CMLock::~CMLock() { pthread_mutex_destroy(&m_mutex); }

int CMLock::trylock() { return pthread_mutex_trylock(&m_mutex); }

int CMLock::lock(const char *func, int line)
{
    while (trylock() != 0)
    {
        // lock fail
        if (m_lastPrintTime == 0)
            m_lastPrintTime = time(NULL);
        if (time(NULL) - m_lastPrintTime > m_printInterval)
        {
            m_lastPrintTime = time(NULL);
            if (m_logprint)
            {
                char data[1024] = {0};
                sprintf(data, "lock dead, last lock at [%s:%d]\n",
                        m_lastFunc.c_str(), m_lastLine);
                m_logprint(3, data);
            }
        }
        usleep(10000);
    }
    m_lastFunc = func;
    m_lastLine = line;
    return 0;
}

int CMLock::unlock()
{
    m_lastPrintTime = 0;
    return pthread_mutex_unlock(&m_mutex);
}
